package com.zhuhjay.boot.config;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ConsumerConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.spring.AnnotationBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Objects;

/**
 * 2.0.1版本SpringBoot 使用构造器注入会抛出异常？
 * 试了很久的 @ConfigurationProperties 一直注入失败
 * 索性尝试 EnvironmentAware 来获取环境变量, 麻了
 * @author ZhuHJay
 * @date 2022/4/1 21:24
 */
@Configuration
public class CustomDubboConfiguration implements EnvironmentAware {

    private String applicationName;
    private String registryAddress;
    private Integer timeOut;
    private boolean check;
    private String packageScan;

    @Bean
    public ApplicationConfig applicationConfig(){
        ApplicationConfig applicationConfig = new ApplicationConfig();
        applicationConfig.setName(applicationName);
        return applicationConfig;
    }

    @Bean
    public RegistryConfig registryConfig(){
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress(registryAddress);
        return registryConfig;
    }

    @Bean
    public ConsumerConfig consumerConfig(){
        ConsumerConfig consumerConfig = new ConsumerConfig();
        // 配置超时时间为10分钟
        consumerConfig.setTimeout(timeOut);
        // 是否检查服务方
        consumerConfig.setCheck(check);
        return consumerConfig;
    }

    @Bean
    public AnnotationBean annotationBean(){
        AnnotationBean annotationBean = new AnnotationBean();
        annotationBean.setPackage(packageScan);
        return annotationBean;
    }

    @Override
    public void setEnvironment(Environment environment) {
        // 使用容器内置组件来进行环境变量的获取
        applicationName = environment.getProperty("custom.dubbo.application-name");
        registryAddress = environment.getProperty("custom.dubbo.registry-address");
        timeOut = Integer.parseInt(Objects.requireNonNull(environment.getProperty("custom.dubbo.time-out")));
        check = Boolean.parseBoolean(environment.getProperty("custom.dubbo.check"));
        packageScan = environment.getProperty("custom.dubbo.package-scan");
    }
}
